package subscriber;

import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

import com.prosyst.util.ref.Log;

public class Activator implements BundleActivator, EventHandler {

	private static final String SUCCESS_EVENT_TOPIC = "libraryservice/search/event/success";
	private static final String FAIL_EVENT_TOPIC = "libraryservice/search/event/fail";

	private BundleContext bundleContext;
	private ServiceRegistration eventHandlerServiceReg;
	private Log log;

	public void start(BundleContext bundleContext) throws Exception {
		this.bundleContext = bundleContext;

		initializeLog();

		// success event
		Dictionary successEventPropertyMap = new Hashtable();
		successEventPropertyMap.put(EventConstants.EVENT_TOPIC, new String[] {
				SUCCESS_EVENT_TOPIC, FAIL_EVENT_TOPIC });
		eventHandlerServiceReg = bundleContext.registerService(
				EventHandler.class.getName(), this, successEventPropertyMap);

	}

	public void stop(BundleContext bundleContext) throws Exception {
		log.close();
		log = null;

		eventHandlerServiceReg.unregister();
		eventHandlerServiceReg = null;

		this.bundleContext = null;
	}

	public void handleEvent(Event event) {
		if (event.getTopic().equals(SUCCESS_EVENT_TOPIC)) {
			log.info("SUBSCRIBER: [SUCCESS - EventHandler] Event property FOUND_BOOK_NAME: "
					+ event.getProperty("BOOK_NAME"));
			log.info("SUBSCRIBER: [SUCCESS - EventHandler] Event property COMMON_COUNTER: "
					+ event.getProperty("COMMON_COUNTER"));
		}

		if (event.getTopic().equals(FAIL_EVENT_TOPIC)) {
			log.info("SUBSCRIBER: [FAIL - EventHandler] Event property NOT_FOUND_BOOK_NAME: "
					+ event.getProperty("BOOK_NAME"));

			log.info("SUBSCRIBER: [FAIL - EventHandler] Event property COMMON_COUNTER: "
					+ event.getProperty("COMMON_COUNTER"));
		}

	}

	private void initializeLog() {
		log = new Log(bundleContext);
		log.setLogLevel(Log.INFO);
		log.setPrintLevel(Log.INFO);
	}
}
